//
//  LoginViewModel.swift
//  SwiftProject
//
//  Created by qindong on 2021/3/16.
//

import RxCocoa

class LoginViewModel: NSObject {
    // 手机号验证
    private let validatePhoneNumber : Driver<Bool>
    //验证码输入验证
    private let validateCode : Driver<Bool>
    //登录按钮可用观察序列
    let validateLoginButton : Driver<Bool>
    
    var buttonIsSelected = BehaviorRelay(value: false)

    init(phoneNumber : Driver<String>, code: Driver<String>) {
        //正则:查找数字
        let numRegularExpression = try! NSRegularExpression(pattern: "[0-9]", options: .caseInsensitive)
        
        validatePhoneNumber = phoneNumber.map({ phoneNumberText in
            //查找输入内容中的数字
            let numMatchCount = numRegularExpression.numberOfMatches(in: phoneNumberText, options: .reportProgress, range: NSRange(location: 0, length: phoneNumberText.count))
            //输入为空或长度小于11
            if phoneNumberText.count == 0 || phoneNumberText.count < 11 { return false }
            //输入内容中存在非数字字符
            if numMatchCount != phoneNumberText.count { return false }
            return true
        })
        
        validateCode = code.map({ codeText in
            let numMatchCount = numRegularExpression.numberOfMatches(in: codeText, options: .reportProgress, range: NSRange(location: 0, length: codeText.count))
            if numMatchCount != codeText.count { return false }
            if codeText.count == 0 || codeText.count < 6 { return false }
            return true
        })
        
        validateLoginButton = Driver.combineLatest(validatePhoneNumber, validateCode, buttonIsSelected.asDriver(), resultSelector: {(phoneNumberIsValid, codeIsValid, buttonIsSelected) -> Bool in
            (phoneNumberIsValid && codeIsValid && buttonIsSelected)
        }).distinctUntilChanged()
    }
}
